/*
 * parser.c
 *
 *      Copyright 2009 Thadeu Ferreira de Melo <thadeu.afm@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 *
 *  Created on: Mar 31, 2009
 *      Author: thadeumelo
 */


#define MAXARG 100
#define NUMARG 10

static char *my_argv[MAXARG];


int parser(char *cmd_lin){
	
	char *cmd_temp = cmd_lin;
	int index = 0;
	int opt = 0;
	char arg[MAXARG];

	bzero(arg, MAXARG);

	while(*cmd_temp != '\0') {
		if(index == NUMARG)
			break;


		/*Passa a considerar palavras entre "aspas" 
			como um unico argumento*/
		if(*cmd_temp == '\"')
			do{
				strncat(arg, cmd_temp, 1);
				cmd_temp++;
			}while(*cmd_temp != '\"');

		if((*cmd_temp == ' ')&& (*cmd_temp != '\0')){

			while(*cmd_temp == ' ')
			{
				cmd_temp++;
				opt = 1;
			}
			if (opt) cmd_temp--;

			if(my_argv[index] == NULL)
				my_argv[index] = (char *)malloc(sizeof(char) * strlen(arg) + 1);
			else {
				bzero(my_argv[index], strlen(my_argv[index]));
			}
			strncpy(my_argv[index], arg, strlen(arg));
			strncat(my_argv[index], "\0", 1);
			bzero(arg, MAXARG);
			index++;
		} else {
			strncat(arg, cmd_temp, 1);
		}
		cmd_temp++;
	}
	if(arg[0] != '\0') { 
		my_argv[index] = (char *)malloc(sizeof(char) * strlen(arg) + 1);
		strncpy(my_argv[index], arg, strlen(arg));
		strncat(my_argv[index], "\0", 1);
	}

	return index;
}

